package com.youngball.shiro.dao;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.youngball.shiro.entity.UserMenus;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by liaopingzhu on 2017/1/12.
 */
//@Repository(value = "shiroCacheRedisDao")
public class ShiroCacheRedisDao {

    private final JedisPool jedisPool;

    private RuntimeSchema<UserMenus> schema = RuntimeSchema.createFrom(UserMenus.class);

    public ShiroCacheRedisDao(String ip, int port) {
        jedisPool = new JedisPool(ip, port);
    }

    /**
     * 登陆后设置用户到redis中
     * @param userMenus
     * @return
     */
    public String setLoginUser(UserMenus userMenus){
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "loginuser:" + userMenus.getUser().getId();
                byte[] bytes = ProtostuffIOUtil.toByteArray(userMenus, schema,
                        LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
                // 超时缓存设为一天
                int timeout = 60 * 60 * 24;
                String result = jedis.setex(key.getBytes(),timeout,bytes);
                return result;
            }finally {
                jedis.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从redis中取出登陆用户
     * @param userId
     * @return
     */
    public UserMenus getLoginUser(Long userId){
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "loginuser:" + userId;
                byte[] bytes = jedis.get(key.getBytes());
                if (bytes != null) {
                    UserMenus userMenus = schema.newMessage();
                    ProtostuffIOUtil.mergeFrom(bytes, userMenus, schema);
                    return userMenus;
                }
            } finally {
                jedis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
